﻿/// <reference path="../jquery-1.4.4.js" />
/// <reference path="../jquery-1.4.4-vsdoc.js" />

/*!  
** Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
** Dual licensed under the MIT and GPL licenses:
** http://www.opensource.org/licenses/mit-license.php
** http://www.gnu.org/licenses/gpl.html
** 
**----------------------------------------------------------------
** title        : DJME pager
** version   : 2.0.2
** modified: 2010-2-22
** depends:
**    jquery.ui.core.js
**    jquery.ui.widget.js
**----------------------------------------------------------------
*/

(function ($) {
    $.widget("ui.pager", {
        options: {
            totalpages: 50,
            totalrecords: 0,
            pageindex: 1,
            pagesize: 20,
            changed: null
        },
        _create: function () {
            var self = this, opts = this.options, el = this.element, eventPrefix = this.widgetEventPrefix;
            el.css({ height: 25 });

            opts.totalpages = parseInt(opts.totalrecords / opts.pagesize) + (opts.totalpages % opts.pagesize ? 1 : 0);
            if ($.isFunction(opts.changed)) {
                el.bind(eventPrefix + "changed", opts.changed);
            }

            var $summary = $("<span/>").addClass("d-pager-summary").appendTo(el);
            $summary.css({ "float": "right" }).text(self._format("Page {0} of {1} ({2} items)", opts.pageindex, opts.totalpages ? opts.totalpages : 1, opts.totalrecords));

            if (opts.totalpages == 0) return;

            var $ul = $("<ul/>").appendTo(el)
                                          .addClass("ui-helper-reset"),

            $first = $("<li/>").appendTo($ul)
                                       .addClass("ui-pager-first")
                                       .append($("<span/>").addClass("ui-icon ui-icon-triangle-1-w")),

            $prev = $("<li/>").appendTo($ul)
                                       .addClass("ui-pager-prev")
                                       .append($("<span/>").addClass("ui-icon ui-icon-carat-1-w")),

            $last = $("<li/>").addClass("ui-pager-last")
                                      .append($("<span/>").addClass("ui-icon ui-icon-triangle-1-e")),

            $next = $("<li/>").addClass("ui-pager-next")
                                       .append($("<span/>").addClass("ui-icon ui-icon-carat-1-e"));


            $first.bind("click", function () {
                self.go(1, $(this));
                $first.hide();
                $prev.hide();
                $last.show();
                $next.show();
            });

            $prev.bind("click", function () {
                self.go(opts.pageindex - 1, $(this));
                if (opts.pageindex == 1) {
                    $first.hide();
                    $prev.hide();
                    $last.show();
                    $next.show();
                }
                else {
                    $last.show();
                    $next.show();
                }
            });

            if (opts.pageindex == 1) { // no forward
                $first.hide();
                $prev.hide();
            }

            var _range = this._updateRange();

            //PageNums
            for (i = _range[0]; i <= _range[1]; i++) {
                var $num = $("<li>" + i.toString() + "</li>").appendTo($ul)
                                                                               .addClass("ui-page-num")
                                                                               .attr("index", i);
                //currentpage is do nothing
                if (opts.pageindex == i)
                    $num.addClass("ui-state-active");
                $num.bind("click", function () {
                    self.go(parseInt($(this).attr("index")), $(this));
                });
            }

            $ul.append($next);
            $ul.append($last);

            //Move next//Move last

            $last.bind("click", function () {
                self.go(opts.totalpages, $(this));
                $first.show();
                $prev.show();
                $last.hide();
                $next.hide();
            });
            $next.bind("click", function () {
                self.go(opts.pageindex + 1, $(this));
                if (opts.pageindex == opts.totalpages) {
                    $first.show();
                    $prev.show();
                    $last.hide();
                    $next.hide();
                }
                else {
                    $prev.show();
                    $first.show();
                }
            });

            if (opts.pageindex == opts.totalpages) {
                $last.hide();
                $next.hide();
            }

            var _btns = $(">li", $ul);
            _btns.each(function () {
                var _btn = $(this);
                _btn.addClass("ui-state-default")
                      .css({
                          "float": "left",
                          width: 16,
                          cursor: "pointer",
                          margin: "1px",
                          padding: "3px",
                          "text-align": "center"
                      });
                _btn.hover(function () { $(this).addClass("ui-state-hover"); }, function () { $(this).removeClass("ui-state-hover"); });
            });
        },
        _format: function () {
            if (arguments.length == 0)
                return null;

            var str = arguments[0];
            for (var i = 1; i < arguments.length; i++) {
                var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
                str = str.replace(re, arguments[i]);
            }
            return str;
        },
        _updateRange: function () {
            var opts = this.options, startAt = 1, end = 11;

            while (opts.pageindex >= end) {
                startAt = startAt + 10;
                end = end + 10;
            }

            if (end > opts.totalpages)
                end = opts.totalpages;

            this.range = [startAt, end];
            return this.range;
        },
        destroy: function () {
            this.element.unbind();
            $("ul>li", this.element).unbind();
            $.Widget.prototype.destroy.call(this);
        },
        reset: function (_total) {
            var opts = this.options;
            opts.pageindex = 1;
            opts.totalrecords = _total;
            this.element.empty();
            this._create();
        },
        _refresh: function () {
            var _range = this._updateRange(), opts = this.options,
            _nums = $(".ui-page-num", this.element);
            _nums.removeClass("ui-state-active");
            _nums.each(function (i, n) {
                _index = i + _range[0];
                if (_index > opts.totalpages) {
                    $(this).hide();
                }
                else {
                    $(this).attr("index", _index)
                             .show()
                             .text(_index);
                    if (_index == opts.pageindex)
                        $(this).addClass("ui-state-active");
                }
            });
        },
        reload: function () {
            this.element.trigger(this.widgetEventPrefix + "changed", { pageIndex: this.options.pageindex, pageSize: this.options.pagesize });
        },
        go: function (_index, _btn) {
            var opts = this.options, self = this, el = this.element, eventPrefix = this.widgetEventPrefix;
            opts.pageindex = _index;
            //el.trigger(eventPrefix + "changed", { pageIndex: _index, pageSize: opts.pagesize });
            el.trigger(eventPrefix + "changed", { pageIndex: _index, pageSize: opts.pagesize });
            if (_btn.hasClass("ui-page-num")) {
                $("li", el).removeClass("ui-state-active");
                _btn.addClass("ui-state-active");
            } else {
                // go next or last
                if (_index > this.range[1]) {
                }
                this._refresh();
            }
        }
    });
})(jQuery);
